package com.yyz.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyz.lease.common.constant.RedisConstant;
import com.yyz.lease.common.exception.LeaseException;
import com.yyz.lease.common.result.ResultCodeEnum;
import com.yyz.lease.common.utils.CodeUtil;
import com.yyz.lease.common.utils.JwtUtil;
import com.yyz.lease.common.utils.ThreadLocalUtil;
import com.yyz.lease.model.entity.UserInfo;
import com.yyz.lease.model.enums.BaseStatus;
import com.yyz.lease.web.app.service.LoginService;
import com.yyz.lease.web.app.service.SmsService;
import com.yyz.lease.web.app.service.UserInfoService;
import com.yyz.lease.web.app.vo.user.LoginVo;
import com.yyz.lease.web.app.vo.user.UserInfoVo;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final SmsService smsservice;
    private final StringRedisTemplate redisTemplate;
    private final UserInfoService userInfoService;

    /**
     * 获取验证码
     */
    @Override
    public void getCode(String phone) {
        //1. 检查手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //2. 检查Redis中是否已经存在该手机号码的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        boolean hasKey = Boolean.TRUE.equals(redisTemplate.hasKey(key));
        if (hasKey) {
            //若存在，则检查其存在的时间
            Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            assert ttl != null;
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - ttl < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //若存在时间不足一分钟，响应发送过于频繁
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        String code = CodeUtil.getCode(6);
        smsservice.sendCode(phone, code);

        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    /**
     * 登录，注册
     */
    @Override
    public String login(LoginVo loginVo) {
        //手机号码为空
        if (loginVo.getPhone() == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //验证码为空
        if (loginVo.getCode() == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

//        String code = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
//        //验证码已过期
//        if (code == null) {
//            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
//        }
//        //验证码错误
//        if (!loginVo.getCode().equals(code)) {
//            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
//        }

        //判断用户是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        if (userInfo == null) {
            //不存在，注册
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }

        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }

    /**
     * 获取用户信息
     */
    @Override
    public UserInfoVo getUserInfo() {
        Claims claims = ThreadLocalUtil.get();
        Long userId = claims.get("userId", Long.class);
        UserInfo userInfo = userInfoService.getById(userId);
        return new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
    }
}
